package com.zst.common.buffer;

import java.util.List;

public class Buffer<T> {
    private T[] content;
    private int size;
    private AtomicRangeInteger index;

    public Buffer(int size) {
        this.size = size;
        this.content = (T[]) new Object[size];
        index = new AtomicRangeInteger(0, size);
    }

    public boolean add(T obj) {
        int i = index.next();
        if (content[i] == null) {
            content[i] = obj;
            return true;
        } else {
            return false;
        }
    }

    public void drainTo(List<T> target) {
        for (int i = 0; i < size; i++) {
            if (content[i] != null) {
                target.add(content[i]);
                content[i] = null;
            }
        }
    }
}
